package cn.jly.spring.jdbc.service;

import cn.jly.spring.jdbc.bean.Account;
import cn.jly.spring.jdbc.dao.TransactionTransferDao;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * @author lanyangji
 * @description
 * @date 2020/11/11 下午 4:35
 */
@Service
public class TransactionTransferServiceImpl implements TransactionTransferService {

    private TransactionTransferDao transferDao;

    public TransactionTransferServiceImpl(TransactionTransferDao transferDao) {
        this.transferDao = transferDao;
    }

    @Transactional(rollbackFor = RuntimeException.class,
            propagation = Propagation.REQUIRED,
            isolation = Isolation.READ_COMMITTED,
            timeout = 20)
    @Override
    public void transfer(String sender, String receiver, BigDecimal money) {
        // 先查有没有发送者
        try {
            transferDao.getByUsername(sender);
        } catch (Exception e) {
            throw new RuntimeException("查无此人 ： " + sender);
        }
        // sender减钱
        final Account senderAccount = new Account();
        senderAccount.setUsername(sender);
        senderAccount.setMoney(money);
        transferDao.updateMoneyByUsername(senderAccount);

        // 再查有没有接收人 - 如果这个时候发生了异常，上面减去钱的方法已经提交，所以需要事物
        try {
            transferDao.getByUsername(receiver);
        } catch (Exception e) {
            throw new RuntimeException("查无此人 ： " + receiver);
        }
        // receiver加钱
        final Account receiverAccount = new Account();
        receiverAccount.setUsername(receiver);
        receiverAccount.setMoney(BigDecimal.valueOf(-money.doubleValue()));
        transferDao.updateMoneyByUsername(receiverAccount);
    }
}
